import { ActionContext, Module } from 'vuex'
import { RootState } from '../index'
import router from '@/router'
import Layout from '@/layout/index.vue'
import asyncRoutes from '@/router/asyncRoutes'
import { userInfo } from '@/api/user'
const modules = import.meta.glob('/src/pages/**/*.vue')

export interface userState {
  token: string
  userInfo: object
  roles: string[]
  menuList: any
}

export const user: Module<userState, RootState> = {
  namespaced: true,
  state: {
    token: '', // token
    userInfo: {}, // 用户信息
    roles: [], // 用户角色的按钮权限列表
    // 菜单列表（动态路由）
    menuList: [{}]
  },
  mutations: {
    // 设置token
    SET_TOKEN(state: userState, str: string) {
      state.token = str
    },
    // 设置用户信息
    SET_USERINFO(state: userState, obj: object) {
      state.userInfo = obj
    },
    // 设置用户角色的按钮权限列表
    SET_ROLES(state: userState, arr: string[]) {
      state.roles = arr
    },
    // 添加动态路由
    SET_MENULIST(state: userState, arr: any) {
      state.menuList = arr
    }
  },
  actions: {
    // 从后端获取用户信息及用户权限信息
    GET_USERINFO({ commit }: ActionContext<userState, RootState>) {
      return new Promise(async resolve => {
        // const res: any = await userInfo()
        const res: any = {
          data: {
            userName: 'zls',
            userCode: '001',
            roles: ['sys:dept', 'sys:document', 'sys:systenConfig', 'sys:deleteDept', 'sys:abcf']
          }
        }
        const info = JSON.parse(JSON.stringify(res.data))
        Reflect.deleteProperty(info, 'roles')
        commit('SET_USERINFO', info)
        commit('SET_ROLES', res.data.roles)
        resolve(res)
      })
    },

    // 从后端获取路由表信息（解析后台的路由表信息，将其添加至路由中）
    GET_MENULIST({ commit }: ActionContext<userState, RootState>) {
      return new Promise(resolve => {
        setTimeout(() => {
          const asyncRoutesNew = formatRoutes(asyncRoutes)
          asyncRoutesNew.forEach((v: any) => {
            router.addRoute(v)
          })
          router.addRoute({ path: '/:pathMatch(.*)*', redirect: '/' }) // 地址栏的路由输入错误后直接跳转到第一项
          commit('SET_MENULIST', asyncRoutesNew)
          resolve(asyncRoutesNew)
        }, 300)
      })
    }
  }
}

// 解析后台的路由表信息，将其添加至路由中
function formatRoutes(routes: any) {
  const arr: any = []
  routes.forEach((route: any) => {
    const tmp = { ...route }
    const comp = tmp.component
    if (comp) {
      switch (comp) {
        case 'Layout':
          tmp.component = Layout
          break
        default:
          // vue3中不支持后面这种方式引入路由了： tmp.component = () => import(`@/pages/${comp}/index.vue`)
          tmp.component = modules[`/src/pages/${comp}/index.vue`]
      }
    }
    if (tmp.children && tmp.children.length) {
      tmp.children = formatRoutes(tmp.children)
    }
    // router.addRoute(tmp)  // addRoute不可在此处添加，源码中会报错，因为子路由中的path没有'/'
    arr.push(tmp)
  })
  return arr
}
